package com.example.musiccommunity.UserPage;

import static android.os.Looper.getMainLooper;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.musiccommunity.MainActivity;
import com.example.musiccommunity.NoticeDetail;
import com.example.musiccommunity.R;
import com.example.musiccommunity.bean.Notice;
import com.example.musiccommunity.bean.Record;
import com.example.musiccommunity.bean.Song;
import com.example.musiccommunity.util.GridAdapter;
import com.example.musiccommunity.util.MusicDataLoader;
import com.example.musiccommunity.util.MusicRecommender;
import com.google.android.material.tabs.TabLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.sql.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link Fragment_Home#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Fragment_Home extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public Fragment_Home() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Fragment_Home.
     */
    // TODO: Rename and change types and number of parameters
    public static Fragment_Home newInstance(String param1, String param2) {
        Fragment_Home fragment = new Fragment_Home();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    private EditText etQuery;
    private ImageView search;


    private TabLayout tabTitle;
    private GridView grid;
    BaseAdapter mAdapter = null;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment__home, container, false);
        grid = view.findViewById(R.id.grid);
        tabTitle = (TabLayout)view.findViewById(R.id.tab_title);

        etQuery = view.findViewById(R.id.et_query);
        search = view.findViewById(R.id.search);
        //软键盘搜索
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str=etQuery.getText().toString();
                setSearch(str);
            }
        });


        tabTitle.setTabMode(TabLayout.MODE_SCROLLABLE);
        //设置tablayout距离上下左右的距离
        //tabTitle.setPadding(20,20,20,20);
        //为TabLayout添加tab名称
        for (int i=0;i<MainActivity.styleArray.size();i++){
            tabTitle.addTab(tabTitle.newTab().setText(   MainActivity.styleArray.get(i)    ));
        }
        tabTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if(tab.getPosition()==0){
                    setRecommend();
                }
                else
                    setStyle(MainActivity.styleArray.get(tab.getPosition()));
                //Toast.makeText(getContext(), MainActivity.styleArray.get(tab.getPosition()), Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        setRecommend();
        return view;
    }
    void setRecommend( ){
//        String url= MainActivity.ip+"/record/get?user="+MainActivity.user.getName();
        String url= MainActivity.ip+"/record/recommendList?user="+MainActivity.user.getName();
        System.out.println(url);
        StringRequest stringRequest=new StringRequest(Request.Method.GET,url, new com.android.volley.Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                System.out.println("_________record/get:"+s);
                if(s==null || s.equals("")){
                    //Toast.makeText(getContext(), "获取数据失败", Toast.LENGTH_SHORT).show();
                }
                else{


                    ArrayList<Record> recordArrayList =new ArrayList<>();
                    JSONObject jsonObject = null;
                    try {
                        JSONArray jsonArray = new JSONArray(s);



                        for (int i=0;i<jsonArray.length();i++){
//                            jsonObject = jsonArray.getJSONObject(i);
//                            String id = jsonObject.get("id").toString();

                            String id =  jsonArray.get(i)+"";
                            Record n=new Record(id
//                                    , jsonObject.get("user").toString(),
//                                    jsonObject.get("style").toString(),
//                                    jsonObject.get("singer").toString()
                            );
                            System.out.println(n);
                            recordArrayList.add(n);
                        }
                        Collections.reverse(recordArrayList);
                        // 初始化推荐器
                        MusicRecommender recommender = new MusicRecommender(MainActivity.songs, recordArrayList);
//                        ArrayList<Song> recommendations = recommender.recommendSongs( 10);
                        ArrayList<Song> recommendations = new ArrayList<>();
                        ArrayList<Song>  recommendation = recommender.recommendSongsNew( jsonArray.length());
                        for(Song songs : recommendation){
                            recommendations.add(songs);
                        }


                        System.out.println("为您推荐以下歌曲：");
                        for(Song song : recommendations) {
                            song.setRandom(false);
                            System.out.printf("- %s (%s) [%s]%n",
                                    song.getName(), song.getArtist(), song.getStyle());
                        }
                        List<Song> random = recommender.getRandomRecommendationsNew( jsonArray.length());
                        for (int i = 0; i <random.size() ; i++) {
                            recommendations.add(random.get(i));
                        }

                        System.out.println("为您随机以下歌曲：");
                        for(Song song : random) {
                            song.setRandom(true);
                            System.out.printf("- %s (%s) [%s]%n",
                                    song.getName(), song.getArtist(), song.getStyle());
                        }




                        mAdapter = new GridAdapter<Song>(recommendations, R.layout.list_song) {
                            @Override
                            public void bindView(ViewHolder holder, Song obj) {


                                TextView recommend = holder.getView(R.id.recommend);
                                holder.setText(R.id.name, obj.getName());
                                holder.setText(R.id.artist, obj.getArtist());
                                int coverResId = MusicDataLoader.getDrawableResourceId(getContext(), obj.getCoverResId());
                                holder.setImageBgResource2(R.id.img,coverResId);

//                                recommend.setVisibility(obj.isRandom()?View.GONE:View.VISIBLE);



                            }
                        };
                        grid.setAdapter(mAdapter);
                        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                Intent intent = new Intent();
                                System.out.println(recommendations.get(i).getName());
                                intent.putExtra("id",recommendations.get(i).getRawResId());
                                intent.setClass(getContext() , PlayMusic.class);
                                startActivity(intent);
                            }
                        });
                    } catch (Exception e) {
                        System.out.println(e.toString());
                        throw new RuntimeException(e);
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("--------",volleyError.toString());
                //Toast.makeText(getContext(), "获取数据失败", Toast.LENGTH_SHORT).show();
            }
        });//字符串
        MainActivity.requestQueue.add(stringRequest);

    }
    void setSearch(String key){
        ArrayList<Song> arrayList=new ArrayList<>();
        for (Song s:MainActivity.songs
        ) {
            if(s.getStyle().contains(key) || s.getAlbum().contains(key)
                    || s.getArtist().contains(key)  || s.getName().contains(key)){
                arrayList.add(s);
            }
        }
        mAdapter = new GridAdapter<Song>(arrayList, R.layout.list_song) {
            @Override
            public void bindView(ViewHolder holder, Song obj) {
                holder.setText(R.id.name, obj.getName());
                holder.setText(R.id.artist, obj.getArtist());
                int coverResId = MusicDataLoader.getDrawableResourceId(getContext(), obj.getCoverResId());
                holder.setImageBgResource2(R.id.img,coverResId);
            }

        };
        grid.setAdapter(mAdapter);
        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent();
                System.out.println(arrayList.get(i).getName());
                intent.putExtra("id",arrayList.get(i).getRawResId());
                intent.setClass(getContext() , PlayMusic.class);
                startActivity(intent);
            }
        });
    }
    void setStyle(String style){
        ArrayList<Song> arrayList=new ArrayList<>();
        for (Song s:MainActivity.songs
             ) {
            if(s.getStyle().equals(style)){
                arrayList.add(s);
            }
        }
        mAdapter = new GridAdapter<Song>(arrayList, R.layout.list_song) {
            @Override
            public void bindView(ViewHolder holder, Song obj) {
                holder.setText(R.id.name, obj.getName());
                holder.setText(R.id.artist, obj.getArtist());
                int coverResId = MusicDataLoader.getDrawableResourceId(getContext(), obj.getCoverResId());
                holder.setImageBgResource2(R.id.img,coverResId);
            }

        };
        grid.setAdapter(mAdapter);
        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent();
                System.out.println(arrayList.get(i).getName());
                intent.putExtra("id",arrayList.get(i).getRawResId());
                intent.setClass(getContext() , PlayMusic.class);
                startActivity(intent);
            }
        });
    }
}